// 博客相关的方法

const {execSQL} = require('../db/mysql');

// 获取博客列表数据
const getBlogsList = (author, keyword) => {
    let sql = `select * from blogs where 1=1 `;

    if(author){
        sql += `and author = '${author}' `;
    }
    if(keyword){
        sql += `and title like '%${keyword}%'`;
    }
    return execSQL(sql);
}

// 获取博客详情数据
const getBlogDetail = (id) => {
    const sql = `select * from blogs where id = '${id}'`;
    return execSQL(sql).then(rows => {
        //console.log('rows', rows);
        return rows[0];
    });
    // // 先返回假数据
    // return {
    //     id: id,
    //     title: '标题1',
    //     content: '内容1',
    //     author: 'zhangsan',
    //     createAt: 1691404634360
    // }
}

// 创建新的博客
const createNewBlog = (blogData = {}) => {
    const title = blogData.title;
    const content = blogData.content;
    const author = blogData.author;
    const createAt = Date.now();
    const sql = `
        insert into blogs (title, content, author, createdAt) values ('${title}', '${content}', '${author}', ${createAt});
    `;
    return execSQL(sql).then(insertedResult => {
        console.log('insertedResult', insertedResult);
        return{
            id: insertedResult.insertId
        }
    });
    // // 把接收的数据存到数据库中
    // console.log('blogData', blogData);
    // return {
    //     id: blogData.id
    // }
}

// 更新博客
const updateBlog = (id, blogData ={}) => {
    console.log('id', id);
    console.log('blogData', blogData);
    return true;
}

// 删除博客
const deleteBlog = (id) => {
    console.log('id', id);
    return true;
}

module.exports = {
    getBlogsList,
    getBlogDetail,
    createNewBlog,
    updateBlog,
    deleteBlog
}